package a.oschina.eventbusdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.bt_click)
    Button mBtClick;
    @BindView(R.id.tv_value)
    TextView mTvValue;
    private boolean isOn = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        mTvValue.setText("今天是星期三");

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isOn) {
                    Log.d("MainActivity", "我在运动");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                isOn = false;
                Log.d("MainActivity", "我在停止");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                isOn=true;
                EventBus.getDefault().post(new MessageEvent("欢迎大家浏览我写的博客"));


            }
        }).start();
    }

    @OnClick({R.id.bt_click})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_click:
                Intent intent = new Intent(MainActivity.this, SeconActivity.class);
                startActivity(intent);
                break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        // mText.setText(messageEvent.getMessage());
       //ThreadMode.POSTING  订阅处理的线程和事件产生位于同一线程中
      //  Only the original thread that created a view hierarchy can touch its views.
        mTvValue.setText(messageEvent.getMessage());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


}
